import 'dart:async';
import 'dart:convert';

import 'package:cached_network_image/cached_network_image.dart';
import 'package:flutter/material.dart';
import 'package:flutter_webview_plugin/flutter_webview_plugin.dart';
import 'package:gzmall_app/common/api.dart';
import 'package:gzmall_app/common/color_common.dart';
import 'package:gzmall_app/common/net_util.dart';
import 'package:gzmall_app/common/open_page_util.dart';
import 'package:gzmall_app/common/setting_util.dart';
import 'package:gzmall_app/common/toast_util.dart';
import 'package:gzmall_app/mine/order_details.dart';
import 'package:gzmall_app/model/advertisement.dart';

class BuySuccessPage extends StatefulWidget {
  String price;
  String orderId;

  BuySuccessPage(this.price, this.orderId);
  @override
  State<StatefulWidget> createState() =>
      BuySuccessPageState(this.price, this.orderId);
}

class BuySuccessPageState extends State<BuySuccessPage> {
  final flutterWebviewPlugin = new FlutterWebviewPlugin();
  String price;
  String orderId;
  List<Advertisement> _advertisements = [];

  StreamSubscription<String> _onWebviewMessaged;

  BuySuccessPageState(this.price, this.orderId);

  @override
  void initState() {
    super.initState();

    _onWebviewMessaged =
        flutterWebviewPlugin.onWebviewMessage.listen((String message) {
      if (message != null && message.isNotEmpty) {
        Map<String, dynamic> params = json.decode(message);
        if (params != null) {
          OpenPageUtil.openPage(
              context, params["type"], params["pageUrl"], params["params"],
              name: params["name"],
              shareTitle: params["shareTitle"],
              shareAvatar: params["shareAvatar"],
              shareContent: params["shareContent"],
              showTips: params["showTips"]);
        }
      }
    });

    _getAdvertisements();
    _getSuccess(orderId);
  }

  @override
  void dispose() {
    super.dispose();
    _onWebviewMessaged.cancel();
    flutterWebviewPlugin.close();
  }

  @override
  Widget build(BuildContext context) {
    double width = MediaQuery.of(context).size.width - 30;
    return Scaffold(
      appBar: _createAppBar(),
      body: ListView(children: <Widget>[
        Container(
          padding: const EdgeInsets.only(bottom: 70.0, top: 70.0),
          color: Colors.white,
          child: Column(
            children: <Widget>[
              Row(
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: <Widget>[
                    Padding(
                      padding: const EdgeInsets.only(right: 15.0),
                      child: Image.asset(
                        "images/pay_result_2.png",
                        width: 28.0,
                        height: 28.0,
                      ),
                    ),
                    Text(
                      "购买成功",
                      style: TextStyle(
                          fontSize: 28.0,
                          color: ColorCommon.black1,
                          fontWeight: FontWeight.bold),
                    ),
                  ]),
              Padding(
                padding: const EdgeInsets.only(top: 10.0, bottom: 70.0),
                child: Text(
                  "实付¥" + this.price ?? "0.0",
                  style: TextStyle(fontSize: 16.0, color: ColorCommon.black1),
                ),
              ),
              Row(
                mainAxisAlignment: MainAxisAlignment.center,
                children: <Widget>[
                  Padding(
                      padding: const EdgeInsets.only(right: 15.0),
                      child: _getButtonView("订单详情", Colors.white,
                          ColorCommon.black1, ColorCommon.grey1, () {
                        flutterWebviewPlugin.close();
                        if (this.orderId != null && this.orderId.isNotEmpty) {
                          Navigator.of(context)
                              .push(MaterialPageRoute(builder: (_) {
                            return OrderDetailsPage(
                                id: int.parse(this.orderId));
                          })).then((v) {
                            Navigator.of(context).pop();
                          });
                        } else {
                          Navigator.of(context)
                              .pushNamed('/order_page')
                              .then((v) {
                            Navigator.of(context).pop();
                          });
                        }
                      })),
                  Padding(
                      padding: const EdgeInsets.only(left: 15.0),
                      child: _getButtonView("返回首页", Colors.white,
                          ColorCommon.black1, ColorCommon.grey1, () {
                        flutterWebviewPlugin.close();
                        Navigator.of(context).pushNamedAndRemoveUntil(
                            '/', (Route<dynamic> r) => false);
                      }))
                ],
              ),
              Padding(
                padding:
                    const EdgeInsets.only(top: 50.0, left: 15.0, right: 15.0),
                child: Column(
                  children: <Widget>[
                    InkWell(
                      onTap: () {
                        if (_advertisements != null &&
                            _advertisements.length > 0) {
                          flutterWebviewPlugin.close();
                          Advertisement adv = _advertisements[0];
                          OpenPageUtil.openPage(
                              context, adv?.pageType, adv?.pageUrl, adv?.params,
                              name: adv?.name);
                        }
                      },
                      child:
                          _advertisements != null && _advertisements.length > 0
                              ? CachedNetworkImage(
                                  imageUrl: _advertisements[0].image,
                                  width: double.infinity,
                                  height: width / 3,
                                  fit: BoxFit.fill,
                                )
                              : Container(
                                  width: double.infinity,
                                  height: width / 3,
                                  color: Colors.grey,
                                ),
                    ),
                    Container(height: 15.0),
                    Row(children: <Widget>[
                      Padding(
                        padding: const EdgeInsets.only(right: 4.0),
                        child: Image.asset(
                          "images/pay_result_1.png",
                          width: 15.0,
                          height: 15.0,
                        ),
                      ),
                      Text(
                        "安全提醒",
                        style: TextStyle(
                            fontSize: 14.0,
                            color: ColorCommon.black1,
                            fontWeight: FontWeight.bold),
                      ),
                    ]),
                    Padding(
                      padding: const EdgeInsets.only(top: 15.0),
                      child: Text(
                        "${SettingUtil.appName}不会通过任何非官方电话，QQ，微信，与您联系，也不会要求您点击链接进行退款或取消订单！",
                        style: TextStyle(
                            fontSize: 14.0, color: ColorCommon.black1),
                      ),
                    ),
                  ],
                ),
              ),
            ],
          ),
        ),
        Container(
          margin: const EdgeInsets.only(top: 10.0),
          height: _url != null && _url.isNotEmpty ? _cardHeight : 0.0,
        ),
      ]),
    );
  }

  _createAppBar() {
    return AppBar(
      elevation: 0.0,
      title: Text("购买成功"),
      leading: IconButton(
        icon: Icon(Icons.arrow_back_ios),
        onPressed: () {
          Navigator.of(context).pop();
        },
      ),
    );
  }

  _getButtonView(String text, Color bgColor, Color contentColor,
      Color borderColor, GestureTapCallback onTap) {
    return Container(
      height: 40.0,
      alignment: Alignment.center,
      padding: const EdgeInsets.only(left: 15.0, right: 15.0),
      decoration: BoxDecoration(
          color: bgColor,
          borderRadius: BorderRadius.circular(100.0),
          border: Border.all(color: borderColor, width: 1.0)),
      child: GestureDetector(
        onTap: onTap,
        child: Text(
          text,
          style: TextStyle(fontSize: 16.0, color: contentColor),
        ),
      ),
    );
  }

  String _url;
  double _cardHeight = 100.0;
  _getSuccess(String orderId) {
    NetUtil.get(
      context,
      Api.orders + "/" + orderId + "/success",
      (data, message) {
        if (!mounted) return;
        setState(() {
          _url = data["scratch_cards_url"];
        });
        flutterWebviewPlugin.close();
        flutterWebviewPlugin.launch(_url,
            rect: new Rect.fromLTWH(
                0.0,
                MediaQuery.of(context).size.height - _cardHeight,
                MediaQuery.of(context).size.width,
                _cardHeight),
            userAgent: Api.kWebViewUserAgent,
            enableMessaging: true);
      },
    );
  }

  _getAdvertisements() {
    Map<String, String> params = {"page_name": "buy_success"};

    NetUtil.get(context, Api.advertisements, (data, message) {
      if (!mounted) return;
      setState(() {
        _advertisements = (data as List)
            ?.map((e) => e == null ? null : Advertisement.fromJson(e))
            ?.toList();
      });
    }, params: params, errorCallBack: (e) {});
  }
}
